from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.database import get_db
from app.models.user import User
from app.models.schemas import UnitViewCreate, UnitViewUpdate, UnitViewResponse
from app.routers.auth import get_current_active_user
from app.services.unit_view_service import unit_view_service
from app.middleware.response_formatter import format_success_response

router = APIRouter()


def is_super_admin(user: User) -> bool:
    """检查用户是否是超级管理员 (is_superuser = 1)"""
    return user.is_superuser == 1


def is_admin_or_super(user: User) -> bool:
    """检查用户是否是管理员（普通管理员或超级管理员）"""
    return user.is_superuser in [1, 2]


@router.get("/")
def get_units(
    page: int = Query(1, ge=1, description="当前页，从1开始"),
    pageSize: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索SN码"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """获取设备视图列表（分页）"""
    # 计算skip值
    skip = (page - 1) * pageSize
    limit = pageSize

    # 获取设备列表和总数
    if search:
        units = unit_view_service.search_units(db, search=search, skip=skip, limit=limit)
        total = unit_view_service.count_search_units(db, search=search)
    else:
        units = unit_view_service.get_multi(db, skip=skip, limit=limit)
        total = unit_view_service.count(db)

    # 转换为响应模型
    unit_list = [UnitViewResponse.from_orm(unit) for unit in units]

    # 返回符合要求的数据结构
    return format_success_response(
        data={
            "list": unit_list,
            "page": page,
            "pageSize": pageSize,
            "total": total,
        },
        message="success",
    )


@router.get("/{unit_id}", response_model=UnitViewResponse)
def get_unit(
    unit_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """根据ID获取设备视图"""
    unit = unit_view_service.get(db, unit_id)
    if unit is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="设备不存在")
    return unit


@router.post("/", response_model=UnitViewResponse)
def create_unit(
    unit_data: UnitViewCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """创建设备视图"""
    if not is_admin_or_super(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="没有权限创建设备"
        )
    
    try:
        unit = unit_view_service.create_unit(db, unit_in=unit_data)
        return unit
    except HTTPException:
        # 重新抛出HTTP异常（如SN码重复错误）
        raise
    except Exception as e:
        print(f"ERROR - 设备创建异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="设备创建时发生错误",
        )


@router.put("/{unit_id}", response_model=UnitViewResponse)
def update_unit(
    unit_id: int,
    unit_update: UnitViewUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """更新设备视图"""
    if not is_admin_or_super(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="没有权限修改设备"
        )

    unit = unit_view_service.get(db, unit_id)
    if unit is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="设备不存在")

    try:
        updated_unit = unit_view_service.update(db, db_obj=unit, obj_in=unit_update)
        if updated_unit is None:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="设备更新失败"
            )
        return updated_unit
    except HTTPException:
        # 重新抛出HTTP异常（如SN码重复错误）
        raise
    except Exception as e:
        print(f"ERROR - 设备更新异常: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="设备更新时发生错误",
        )


@router.delete("/{unit_id}")
def delete_unit(
    unit_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """删除设备视图（仅超级管理员）"""
    if not is_super_admin(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="只有超级管理员可以删除设备"
        )

    unit = unit_view_service.get(db, unit_id)
    if unit is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="设备不存在")

    unit_view_service.remove(db, id=unit_id)
    return {"message": "设备删除成功"}


@router.get("/sn/{sn_code}", response_model=UnitViewResponse)
def get_unit_by_sn(
    sn_code: str,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db),
):
    """根据SN码获取设备视图"""
    unit = unit_view_service.get_by_sn_code(db, sn_code)
    if unit is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="设备不存在")
    return unit
